package com.example.covid19.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.covid19.common.Dto.RegisterDto;
import com.example.covid19.common.Dto.userDto;
import com.example.covid19.common.lang.Result;
import com.example.covid19.entity.User;
import com.example.covid19.entity.UserDiscount;
import com.example.covid19.service.UserDiscountService;
import com.example.covid19.service.UserService;
import com.example.covid19.util.SecretUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.HttpMultipartMode;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.
        hc.client5.http.entity.mime.StringBody;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.example.covid19.util.SecretUtil.secret;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author BaiZhengChun
 * @since 2022-09-12
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final UserDiscountService userDiscountService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public UserController(UserService userService, UserDiscountService userDiscountService) {
        this.userService = userService;
        this.userDiscountService = userDiscountService;
    }

    @RequestMapping("doLogin")
    public Result doLogin(@RequestParam("studentid") String studentid, @RequestParam("password") String password) {
        // 此处仅作模拟示例，真实项目需要从数据库中查询数据进行比对
        User user = userService.getOne(new QueryWrapper<User>().eq(
                "studentid", Integer.valueOf(studentid)
        ));
//        stringRedisTemplate.opsForValue().set("hello", "Hello World");
        if (user == null) {
            return Result.fail(401,"用户不存在",null);
        }
        boolean flag = user.getPassword().equals(
                SecureUtil.hmacSha1(secret)
                        .digestHex(password)
        );
        if(flag) {
            StpUtil.login(user.getUserid());
            System.out.println(StpUtil.getTokenValue());
            return Result.success(200,"登陆成功",StpUtil.getTokenInfo());
        }
        else {
            return Result.fail(400,"密码错误",null);
        }
    }
    @RequestMapping("/logout")
    public void logout(){
        StpUtil.logout();
    }
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDto registerDto) {
        String code = registerDto.getCode();
        String c = stringRedisTemplate.opsForValue().get(registerDto.getPhone());
        System.out.println(stringRedisTemplate.opsForValue().get(registerDto.getPhone()));
        System.out.println(code);
        boolean codeFlag = code.equals(c);
//        redisUtils.deleteKey(registerDto.getPhone());
        if (!codeFlag) {
            return Result.fail(406, "验证码不正确", null);
        }
//        stringRedisTemplate.delete(registerDto.getPhone());
        String secret = SecretUtil.secret;
//        int id = registerDto.getStudentid();
////        int discounr = 1;
       User user = new User();
        user.setStudentid(registerDto.getStudentid());
        user.setUsername(registerDto.getUsername());
        user.setPassword(SecureUtil.hmacSha1(secret).digestHex(registerDto.getPassword()));
        user.setPhone(registerDto.getPhone());
        user.setRole("学生");
        User users = userService.getOne(new QueryWrapper<User>().eq("studentid",registerDto.getStudentid()));
        if (users != null) {
            return Result.fail(406, "用户已经存在", null);
        }
        boolean flag = userService.save(user);
        if (!flag) {
            return Result.fail(406, "用户创建失败", null);
        }
        UserDiscount discount = new UserDiscount();
        discount.setStudentid(registerDto.getStudentid());
        discount.setDiscount(1);
        boolean dFlag = userDiscountService.save(discount);
        System.out.println(user.getStudentid());
        return dFlag ? Result.success(200,"注册成功",null) : Result.fail(406, "用户创建失败", null);

    }
    @PostMapping("/save")
    public void save(@Validated @RequestBody userDto userDto){
        User user = new User();
        user.setClasss(userDto.getClasss());
        user.setMajor(userDto.getMajor());

    }
    @PostMapping ("/getter")
    public void getter(HttpServletRequest httpServletRequest) throws IOException {
        //
    }

    @PostMapping("/sendMsg")
    public void sendMessage(@RequestParam("phone") String phone) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKID73mGVVFk00kFVVFl24qMcdOt9AvQggRw", "HJ5buxlJbdV8WeW9WdU6SYOzKQHvLVv6");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {phone};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId("1400527069");
            req.setSignName("辽东学院");
            req.setTemplateId("972395");
            String code = RandomStringUtils.randomNumeric(6);
            System.out.println(code);
            // 验证码，附加文字，但是不能超过12个字符
            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);
            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            long codeTimeout = 300;
//            redisUtils.setValue(phone, code, codeTimeout);
            stringRedisTemplate.opsForValue().set(phone, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }
}
